<template>
  <div>
    <!-- 上传 -->
    <div class="uploadDiv" v-for="(item, index) in accList" :key="index">
      <div class="title_div">
        <span><b style="color: red">*</b>上传{{ item.info.itemText }} </span>
        <span
          v-if="item.info.itemValue == 6"
          style="font-size: 18px; font-weight: bold"
          >房屋评估总价(<input
            class="inputFW"
            type="text"
            v-model="evaluationPrice"
            readonly
            ondblclick="readOnly=false"
            @blur="PriceOnblur"
          />)万元</span
        >
        <span
                v-if="item.info.itemValue == 8"
                style="font-size: 18px; font-weight: bold"
        >备注：{{intro.note}}</span
        >

        <el-button
          size="small"
          class="downloadImagee"
          @click="downloads1(item)"
          v-if="item.data.length > 0 && item.data[0].type != 2"
          >下载</el-button
        >
<!--        v-if="showFileUpdate && sStatus && showAss"-->
        <el-upload
          class="upload-demo"
          action=""
          :multiple="true"
          :http-request="uploadImg"
          :accept="fileType"
        >
          <span>
            <el-button
              size="small"
              class="addpic"
              @click="changeType(item.info.itemValue)"
              >上传</el-button
            >
          </span>
        </el-upload>
      </div>
      <div
        class="upload_list listCart"
        v-loading="item.info.loading"
        element-loading-text="拼命上传中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        :style="{ 'min-height': `${'height'+index}` +'px' }"
      >
        <ul class="clearfix" :id="'jq' + index">
          <li v-for="(item1, index1) in item.data" :key="item1.id">
            <div v-if="item1.type == 2">
              <div class="img">
                <el-image
                  style="width: 160px; height: 90px"
                  :src="item1.minUrl"
                  fit="cover"
                  :lazy="true"
                >
                </el-image>
              </div>
              <el-tooltip
                class="item"
                effect="dark"
                :content="item1.showName"
                placement="top-start"
              >
                <p class="name">{{ item1.showName }}</p>
              </el-tooltip>
              <p class="ztc">{{ item1.size }} MB</p>
              <p class="ztc">{{ item1.createTime }}上传</p>
              <div class="btn">
                <el-button type="text" @click="reviewVideo(item1)"
                  >查看</el-button
                >
                <span v-if="((item1.type!=6 && showFileDel) || item1.type==6 && showAssessFileDel)  && showAss">
                  <el-popconfirm
                    title="确定删除此数据吗？"
                    @onConfirm="deleteImg(item1.id)"
                  >
                    <el-button
                      slot="reference"
                      type="text"
                      size="small"
                      class="deteBtnText"
                      >删除</el-button
                    >
                  </el-popconfirm>
                </span>
              </div>
            </div>
            <div v-else>
              <img
                style="width: 160px; height: 90px; border-radius: 10px"
                :src="item1.minUrl"
                :ref="index + index1 + `img`"
                :realurl="item1.url"
                :showName="item1.showName"
              />
              <button
                :id="index1"
                class="viewButton"
                @click="viewImg(index, index1 + 'img')"
              >
                查看
              </button>

              <span
                v-if="((item1.type!=6 && showFileDel) || item1.type==6 && showAssessFileDel)  && showAss"
                class="deleteStyle"
              >
                <el-popconfirm
                  title="确定删除此数据吗？"
                  @onConfirm="deleteImg(item1.id)"
                >
                  <el-button
                    slot="reference"
                    type="text"
                    size="small"
                    class="deteBtnText"
                    >删除</el-button
                  >
                </el-popconfirm>
              </span>
              <div class="titleStyle">
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="item1.showName"
                  placement="top-start"
                >
                  <p class="name">{{ item1.showName }}</p>
                </el-tooltip>
                <p class="ztc">{{ item1.size }} MB</p>
                <p class="ztc">{{ item1.createTime }}上传</p>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div>
      <el-dialog
        title="查看视频"
        :visible.sync="dialogVisiblee"
        width="650px"
        class="diaBox"
        :before-close="handleDialogClosee"
      >
        <video
          class="videoStyle"
          :src="src"
          controls="controls"
          autoplay="autoplay"
        ></video>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisiblee = false">关 闭</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {
  getSurveyOss,
  surAddImg,
  delSuryImg,
  getSurResult,
  updateSurData,
} from "../../../src/assets/js/api";
import img from "@/assets/img/surImg.png";
import { checkPermiss } from "../../assets/js/utlis";

import JSZip from "jszip";
import FileSaver from "file-saver";
export default {
  name: "Upload",
  data() {
    return {
      evaluationPricess: "",
      sid: null,
      evaluationPrice: "",
      widths: "px",
      boxs: "inline - block",
      width: "",
      height: "",
      srcs: "", //遮罩层大图地址！
      imgIndex: "",
      showViewer: false, //遮罩层开关!
      indexList: [], //遮罩层轮播图数组!
      dialogVisiblee: false, //视频弹窗!
      imageSwitch: false, //图片放大弹窗开关!
      maskImage: null, //遮罩层图片地址!
      indexNumber: null, //数组索引!
      imgNumber: null, //轮播图数据!
      videoImg: img,
      address: [], //各类型图片地址!
      imageName: [], //各类型图片名称!
      buildName: null, //打包名字!
      dialogVisible: false,
      imgUpdateUrl: "",
      loading0: false,
      loading1: false,
      loading2: false,
      loading3: false,
      loading4: false,
      loading5: false,
      loading6: false,
      accList: [],
      stsdata: null,
      /*sfList: [], //身份证照片列表!
        houseList: [], //房产证照片!
        videoList: [], //房屋房屋视频!
        conList: [], //签约文件!
        viewList: [], //房屋外观照!
        inHoseList: [], //房屋照!
        assList: [], //评估文件!*/
      type: 0,
      src: "",
      previewList: [],
      height0: "0",
      height1: "0",
      height2: "0",
      height3: "0",
      height4: "0",
      height5: "0",
      height6: "0",
      golbalPermissions: [],
      fileType: "",
      readOnly: false,
      intro: {}
    };
  },
  props: ["id", "imgList", "sStatus", "showAss", "isSurvey"],
  watch: {
    imgList: {
      handler(val) {
        let list = JSON.parse(JSON.stringify(val));
        this.accList = list;


        for (let key in list) {
          this.$nextTick(() => {
            new window.Viewer(document.getElementById("jq" + key));
          });
        }

        for (let key in  this.accList) {
          let obj={loading:false};
          this.accList[key].info= Object.assign(obj,   this.accList[key].info)

        }

      },
      deep: true, //true 深度监听
    },
    // evaluationPrice: {
    //   handler(val) {
    //     console.log(val.length,"1231")
    //     this.evaluationPricess = val.length * 20 + "px";
    //     console.log(this.evaluationPricess, "123");
    //   },
    //   deep: true, //true 深度监听

    // },
  },
  computed: {
    //附件查看
    showSurRev: function () {
      return checkPermiss("static:survey:img", this.golbalPermissions);
    },
    //附件删除
    showFileDel: function () {
      return checkPermiss("business:survey:deleteImg", this.golbalPermissions);
    },
    //评估附件删除
    showAssessFileDel: function () {
      return checkPermiss("business:assess:deleteImg", this.golbalPermissions);
    },
    //附件上传
    showFileUpdate: function () {
      return checkPermiss("business:survey:getMap", this.golbalPermissions);
    },
  },
  created() {
    this.golbalPermissions = localStorage.getItem("permissions").split(",");
    //this.SJpermissions = sessionStorage.getItem("reviewer");
    this.SurveyPermission = sessionStorage.getItem("surveyer");
    this.getInfo();
  },
  mounted() {},
  methods: {
    getInfo() {
      getSurResult(this.id).then((res) => {
        this.evaluationPrice = res.data.tbSurveyDataVo.evaluationPrice;
        this.sid = res.data.tbSurveyDataVo.id;
        this.intro = res.data.tbSurvey;
      });
    },
    // 房屋评估价输入框失去焦点事件!
    PriceOnblur() {
      this.readOnly = true;
      this.$emit("in-Price", this.evaluationPrice);
      let tbSurveyData = {};
      tbSurveyData.id = Number(this.sid);
      tbSurveyData.evaluationPrice = Number(this.evaluationPrice);
      updateSurData({ tbSurveyData: tbSurveyData }).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          getSurResult(this.id).then((res) => {
            this.evaluationPrice = res.data.tbSurveyDataVo.evaluationPrice;
          });
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 图片查看功能!
    viewImg(index, refName) {
      this.$refs[`${index + refName}`][0].click();
    },
    //获取授权下载地址
    async getOssDownLoadUrl(oldurl, fileName) {
      let url = "";
      if (!this.stsdata) {
        //获取令牌
        await this.axios.get("/business/survey/getStsToken", {}).then((res) => {
          if (res) {
            this.stsdata = res.data.data;
          }
        });
      }
      //创建oss对象
      const OSS = require("ali-oss");
      const client = new OSS({
        // yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
        region: "oss-cn-chengdu",
        // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
        accessKeyId: this.stsdata.accessKeyId,
        accessKeySecret: this.stsdata.accessKeySecret,
        // 从STS服务获取的安全令牌（SecurityToken）。
        stsToken: this.stsdata.securityToken,
        // 填写Bucket名称。
        bucket: "drxf-oss",
      });
      // 配置响应头实现通过URL访问时自动下载文件，并设置下载后的文件名。
      //const filename = fileName // 自定义下载后的文件名。
      const response = {
        "content-disposition": `attachment; filename=${encodeURIComponent(
          fileName
        )}`,
      };
      // 填写Object完整路径。Object完整路径中不能包含Bucket名称。
      url = client.signatureUrl(oldurl.substring(oldurl.indexOf("static")), {
        response,
      });
      return url;
    },
    //定义一个base64打包的方法!
    async packaging(name, baseList, address, num, zipName, loading) {
      //转换为授权下载地址
      address = await this.getOssDownLoadUrl(address, name);
      if (!address) {
        this.$message.error(`请稍候再试`);
        return;
      }
      // packaging方法后面第一个参数name是数组对象的key,baseList是去掉base64编码前的 是存放图片地址的数组,num是存放图片地址数组的长度,zipName是压缩包的名字,loading是模态框!
      let imgName = name; //数组对象的key赋值给imgName!
      let image = new Image();
      // 解决跨域 Canvas 污染问题
      image.setAttribute("crossOrigin", "anonymous");
      image.crossOrigin = "Anonymous";
      image.onload = function () {
        let canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        let context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        let url = canvas.toDataURL("image/jpeg", 0.6); // 得到图片的base64编码数据,默认是jpeg格式!好处,文件小!
        let temp = { [imgName]: url.substring(22) }; //temp等于{对象key:去掉图片的base64编码前22位字符的数据!}key是图片的名字!他的值是图片的地址!
        baseList.push(temp); //把得到的key对象赋值到baseList数组里面!
        var blogTitle = zipName; //声明blogTitle,并且把压缩包的名字赋值给blogTitle!
        var zip = new JSZip();
        var imgs = zip.folder(zipName);
        //如果存放编码后数组的长度等于存放图片地址的长度!
        if (baseList.length === num) {
          //这个for循环拿到数组对象的索引!
          for (var item in baseList) {
            //这个for循环拿到对象的key,也就是图片的名字!
            for (var it in baseList[item]) {
              //imgs.file后面的参数分别是(图片名字,编码后的图片地址,开启base64编码下载!)
              imgs.file(it, baseList[item][it], { base64: true });
            }
          }
          zip.generateAsync({ type: "blob" }).then(function (content) {
            FileSaver.saveAs(content, blogTitle + ".zip");
            loading.close(); //关闭模态框!
          });
        }
      };
      image.src = address;
    },
    async downloads1(data) {
      //this.getOssDownLoadUrl();
      //开启模态框!
      let loading = this.$loading({
        lock: false,
        text: "正在打包下载,请稍等...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      //初始化文件数据
      var dataArray = data.data;
      //初始化类型名称
      this.buildName = data.info.itemText;
      //base64编码去掉前22位字符后的baselist数组!
      var baseList = [];
      // 要下载图片的url
      var arr = this.address;
      // 下载后图片的文件名，个数应与arr对应
      var imgNameList = this.imageName;
      for (let i = 0; i < dataArray.length; i++) {
        this.address.push(dataArray[i].url);

        this.imageName.push(dataArray[i].showName);
      }
      for (var i = 0; i < arr.length; i++) {
        // 这里循环得到图片下载地址,图片名字!
        await this.packaging(
          imgNameList[i],
          baseList,
          arr[i],
          arr.length,
          this.buildName,
          loading
        );
      }
      this.stsdata = null;
      this.address = [];
      this.imageName = [];
      this.buildName = [];
    },
    // 查看视频详情弹窗右上角监听事件!
    handleDialogClosee() {
      this.dialogVisiblee = false; //关闭弹窗!
    },
    changeType(type) {
      this.type = type;
      if (this.type == 2) {
        this.fileType = ".mp4,.ogv,.ogg,.webm";
      }else {
        this.fileType = "";
      }
      //   这里获取到了类型!
    },
    //
    handleExceed() {
      this.$message.warning(
        `当前限制选择1个文件，本次选择了 1
        个文件，共选择了1 个文件`
      );
    },
    //删除照片
    deleteImg(id) {
      delSuryImg(id).then((res) => {
        this.$message({
          message: res.message,
          type: "success",
        });
        //请求一遍数据
        getSurResult(this.id).then((res1) => {
          this.accList = res1.data.mapSurveyAccessory;
        });
      });
    },
    //获取图片尺寸!
    async getData() {
      let that = this;
      let img_url = this.srcs;
      let img = new Image();
      img.src = img_url;
      img.onload = function () {
        that.width = img.width;
        that.height = img.height;
      };
    },
    //查看视频
    reviewVideo(obj) {
      this.src = obj.url;
      this.dialogVisiblee = true;
    },
    //上传照片
    uploadImg(params) {
      let that = this;

      this.accList[`type${this.type}`].info.loading=true;
      // this[`loading${this.type}`] = true;
      this[`height${this.type}`] = 150;
      //从后端获取OSS数据
      getSurveyOss().then((res) => {
        let imgName = params.file.name;
        let wz = imgName.split(".");
        let imgType = "." + wz[wz.length - 1];
        //创建文件
        let formData = new FormData();
        //表头信息
        let config = {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        };
        //上传对象
        let dataOss = res.data;
        let ossUrl = dataOss.host;
        formData.append("policy", dataOss.policy);
        formData.append("key", dataOss.dir + dataOss.fileName + imgType);
        formData.append("OSSAccessKeyId", dataOss.accessid);
        formData.append("Signature", dataOss.signature);
        formData.append("success_action_status", 200);
        formData.append("fileName", dataOss.fileName);
        formData.append("file", params.file);
        //传文件成功后需要的参数
        let fileForm = {
          showName: imgName,
          url: dataOss.fileName,
          size: params.file.size,
          sid: this.id,
          type: this.type,
        };
        this.axios
          .post(ossUrl, formData, config)
          .then((res) => {
            if (res.status == 200) {
              that.addImg(fileForm);
            }
          })
          .catch(() => {
            this.accList[`type${this.type}`].info.loading=false;
            // that[`loading${this.type}`] = false;
            that[`height${this.type}`] = 0;
          });
      });
    },
    //图片上传成功调用的函数
    addImg(params) {
      let that = this;
      surAddImg(params)
        .then((res) => {
          // let resData = res.data;
          this.$message({ message: res.message, type: "success" });
          //请求一遍数据
          getSurResult(this.id).then((res1) => {
            this.accList = res1.data.mapSurveyAccessory;
          });
          this.accList[`type${this.type}`].info.loading=false;
          // that[`loading${this.type}`] = false;
          that[`height${this.type}`] = 0;
          //   location.reload();
        })
        .catch(() => {
          this.accList[`type${this.type}`].info.loading=false;
          // that[`loading${this.type}`] = false;
          that[`height${this.type}`] = 0;
        });
    },
  },
};
</script>

<style scoped>
.diaBox {
  min-width: 580px;
}
::v-deep .el-upload-list {
  display: none;
  width: 100%;
}
.title_div {
  line-height: 56px;
  height: 56px;
  text-align: left;
  border-bottom: 1px solid #ededed;
}
.previewImg {
  width: 100%;
  height: 100%;
}
.title_div span {
  font-family: Microsoft YaHei;
  font-size: 15px;
  font-weight: 400;
  position: relative;
  height: 15px;
  color: rgba(51, 51, 51, 1);
}
.upload-demo {
  display: inline-block;
  float: right;
}
.addpic {
  color: #fff !important;
  border: 1px solid #ffa32f !important;
  background: #ffa32f !important;
}
.addpic:hover {
  color: #fff;
  border: 1px solid #ffa32f;
  background: #ffa32f;
}
.uploadDiv {
  position: relative;
  overflow: hidden;
  margin-top: 10px;
}
.upload_list {
  overflow: hidden;
}
.upload_list ul {
  margin-right: -12px;
}
.upload_list li {
  position: relative;
  float: left;
  box-sizing: border-box;
  width: 49%;
  height: 130px;
  margin-top: 20px;
  margin-right: 20px;
  padding: 20px;
  text-align: left;
  border: 1px solid rgba(237, 237, 237, 1);
  border-radius: 8px;
}
.upload_list li:nth-child(even) {
  margin-right: unset;
}
.upload_list .img {
  float: left;
  overflow: hidden;
  width: 160px;
  height: 90px;
  margin-right: 20px;
  border-radius: 6px;
}
.upload_list .btn {
  position: absolute;
  top: 20px;
  right: 20px;
}
.upload_list .name {
  font-family: Microsoft YaHei;
  font-size: 14px;
  font-weight: 400;
  overflow: hidden;
  max-width: 66%;
  max-height: 20px;
  margin-top: 5px;
  margin-bottom: 14px;
  color: rgba(51, 51, 51, 1);
}
.upload_list .ztc {
  color: #999;
}

.el-carousel__item h3 {
  font-size: 14px;
  line-height: 150px;
  margin: 0;
  opacity: 0.75;
  color: #475669;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}
.downloadImagee {
  position: absolute;
  top: 13px;
  right: 60px;
  color: #fff;
  border: 1px solid #ffa32f;

  /* color: #fff !important;
      background: #ffa32f !important;
      border: 1px solid #ffa32f !important;
      position: absolute;
      right: 60px;
      top: 13px; */
  background: #ffa32f;
}
.videoStyle {
  width: 100%;
  height: 100%;
}

.viewButton {
  font-size: 14px;
  position: absolute;
  top: 10px;
  right: 40px;
  display: inline-block;
  width: 50px;
  height: 26px;
  cursor: pointer;
  color: #409eff;
  border: 1px solid transparent;
  background-color: transparent;
}
.deleteStyle {
  font-size: 14px;
  position: absolute;
  top: 12px;
  right: 0;
  display: inline-block;
  width: 50px;
  height: 26px;
  cursor: pointer;
  color: #409eff;
  border: 1px solid transparent;
  background-color: transparent;
}
.titleStyle {
  position: absolute;
  top: 12px;
  left: 200px;
}
.inputFW {
  text-align: center;
  width: 105px;
  border: 0;
  color: red;
  font-weight: bold;
  /* font-size: 30px; */
}
</style>
